﻿using System;
using System.Xml;
using System.Windows.Forms;

namespace AutoMerge
{
    public class UpdateMachineManifest
    {
        public static void update(string filePath, string siteServer, string dataServer, RichTextBox tb)
        {
            try
            {
                tb.AppendText("\r\n");
                tb.AppendText(@"updating MachineManifest file--------------------------------------------------------------" + "\r\n");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(filePath);

                XmlNodeList xnl = xmldoc.SelectNodes("//configuration/ijv.platform.manifest/deploymentUnits/add/roles/add");

                XmlElement temp;
                XmlNode xnTemp;
                XmlElement xeTemp;

                //when category is application, the flag is true, otherwise, it is false.
                bool flag = true;

                //configure the note with deployPath="E:\webroot"
                tb.AppendText(@"configuring node:  deployPath to E:\webroot" + "\r\n");
                XmlNode xn = xmldoc.SelectSingleNode("//configuration/settings/add");
                ((XmlElement)xn).SetAttribute("value", @"E:\webroot");


                //search all the notes, and set the machine name according to different category
                foreach (XmlNode xmlnode in xnl)
                {
                    temp = (XmlElement)xmlnode;

                    if (temp.GetAttribute("name") == "RenderingData")
                    {
                        flag = false;
                    }

                    if (flag)
                    {
                        tb.AppendText("configuring node:  " + temp.GetAttribute("name") + "..." + "\r\n");
                        xnTemp = temp.SelectSingleNode(@"machines/add");
                        xeTemp = (XmlElement)xnTemp;
                        xeTemp.SetAttribute("name", siteServer);
                    }
                    else
                    {
                        tb.AppendText("configuring node:  " + temp.GetAttribute("name") + "..." + "\r\n");
                        xnTemp = temp.SelectSingleNode(@"machines/add");
                        xeTemp = (XmlElement)xnTemp;
                        xeTemp.SetAttribute("name", dataServer);
                    }
                }
                xmldoc.Save(filePath);
            }

            catch (Exception ex)
            {
                tb.AppendText("Error occure when updating the MachineManifest file, program will stopped..." + "\r\n");
                tb.AppendText(ex + "\r\n");
                throw new Exception("custom");
            }
        }
    }
}
